package com.iflytek.aidemo;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ImageButton;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.iflytek.aidemo.model.User;
import com.iflytek.aidemo.student.WrongQuestionActivity;
import com.iflytek.aidemo.student.WrongPushScheduler;
import com.iflytek.aidemo.student.WrongPushStore;
import com.iflytek.aidemo.teacher.ClassManagementActivity;
import com.iflytek.aidemo.util.SessionManager;
import com.iflytek.aidemo.teacher.TeacherScoreOverviewActivity;

import java.io.File;

public class MainActivity extends AppCompatActivity {
    public static final int TAKE_PHOTO = 1;
    public static final int CHOOSE_PHOTO = 2;

    File file = new File(Environment.getExternalStorageDirectory().getPath() + "/video.mp4");
    Uri uri = Uri.fromFile(file);

    private FrameLayout takePhotoContainer;
    private ImageView rippleEffect;
    private AnimatorSet blinkAnimator;
    private AnimatorSet rippleAnimator;
    private TextView tvWelcome, tvUserType;
    private SessionManager sessionManager;
    private ImageButton btnLogout;
    private View redDotWrongBook;
    private BroadcastReceiver redDotUpdateReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        sessionManager = new SessionManager(this);

        setLayoutBasedOnUserType();

        initViews();

        try { WrongPushScheduler.scheduleWeekly(this); } catch (Exception ignored) { }

        View back = findViewById(R.id.btn_back);
        if (back != null) {
            back.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            });
        }

        displayUserInfo();

        createBlinkAnimation();

        createRippleAnimation();

        startBlinkAnimation();

        startRippleAnimation();

// 对照相功能的响应（添加非空判断）
        Button takePhoto = findViewById(R.id.take_photo);
        if (takePhoto != null) {  // 只有找到控件才设置监听器
            takePhoto.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    stopBlinkAnimation();
                    stopRippleAnimation();
                    addClickAnimation(v);
                    v.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            Intent intent = new Intent();
                            intent.setClass(MainActivity.this, ImageAlbumShow.class);
                            Bundle bundle = new Bundle();
                            bundle.putInt("id", TAKE_PHOTO);
                            intent.putExtras(bundle);
                            MainActivity.this.startActivity(intent);
                        }
                    }, 200);
                }
            });
        }

// 设置相册选择的响应（同样添加非空判断）
        Button chooseFromAlbum = findViewById(R.id.choose_from_album);
        if (chooseFromAlbum != null) {  // 只有找到控件才设置监听器
            chooseFromAlbum.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    addClickAnimation(v);
                    v.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            Intent intent = new Intent();
                            intent.setClass(MainActivity.this, ImageAlbumShow.class);
                            Bundle bundle = new Bundle();
                            bundle.putInt("id", CHOOSE_PHOTO);
                            intent.putExtras(bundle);
                            MainActivity.this.startActivity(intent);
                        }
                    }, 200);
                }
            });
        }

        btnLogout = findViewById(R.id.btn_logout);
        btnLogout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new android.app.AlertDialog.Builder(MainActivity.this)
                        .setTitle("确认登出")
                        .setMessage("您确定要退出登录吗？")
                        .setPositiveButton("确定", new android.content.DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(android.content.DialogInterface dialog, int which) {
                                sessionManager.clearSession();
                                Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                startActivity(intent);
                                finish();
                            }
                        })
                        .setNegativeButton("取消", null)
                        .show();
            }
        });

        ImageView btnWrongBook = findViewById(R.id.btn_wrong_book);
        if (btnWrongBook != null) {
            btnWrongBook.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    User currentUser = sessionManager.getCurrentUser();
                    if (currentUser != null) {
                        Intent intent = new Intent(MainActivity.this, WrongQuestionActivity.class);
                        intent.putExtra("student_id", currentUser.getUserId());
                        startActivity(intent);
                    }
                }
            });
        }

        FrameLayout btnViewScores = findViewById(R.id.btn_view_scores);
        if (btnViewScores != null) {
            btnViewScores.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    addClickAnimation(v);
                    v.postDelayed(() -> {
                        Intent intent = new Intent(MainActivity.this, TeacherScoreOverviewActivity.class);
                        startActivity(intent);
                    }, 200);
                }
            });
        }

        FrameLayout btnViewClass = findViewById(R.id.btn_view_class);
        if (btnViewClass != null) {
            btnViewClass.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    addClickAnimation(v);
                    v.postDelayed(() -> {
                        Intent intent = new Intent(MainActivity.this, ClassManagementActivity.class);
                        startActivity(intent);
                    }, 200);
                }
            });
        }
    }

    private void setLayoutBasedOnUserType() {
        User currentUser = sessionManager.getCurrentUser();
        if (currentUser != null) {
            String userType = currentUser.getUserType();
            if (userType != null && !userType.isEmpty()) {
                if (userType.equals("1")) {
                    setContentView(R.layout.activity_main_student);
                } else {
                    setContentView(R.layout.activity_main_teacher);
                }
            } else {
                setContentView(R.layout.activity_main_student);
            }
        } else {
            setContentView(R.layout.activity_main_student);
        }
    }

    private void initViews() {
        takePhotoContainer = findViewById(R.id.take_photo_container);
        rippleEffect = findViewById(R.id.ripple_effect);
        tvWelcome = findViewById(R.id.tv_welcome);
        tvUserType = findViewById(R.id.tv_user_type);
    }

    private void displayUserInfo() {
        User currentUser = sessionManager.getCurrentUser();
        if (currentUser != null) {
            String username = currentUser.getUserName();
            String userType = currentUser.getUserType();

            tvWelcome.setText(" 欢迎，" + username + "！");

            if (userType != null && !userType.isEmpty()) {
                com.iflytek.aidemo.util.CircleImageView ivAvatar = findViewById(R.id.iv_avatar);
                if (ivAvatar != null) {
                    if (userType.equals("1")) {
                        tvUserType.setText("当前身份：学生");
                        ivAvatar.setImageResource(R.mipmap.student);
                    } else {
                        tvUserType.setText("当前身份：老师");
                        ivAvatar.setImageResource(R.mipmap.teacher);
                    }
                }
            } else {
                tvUserType.setText("当前身份：未知");
            }
        } else {
            tvWelcome.setText("欢迎使用！");
            tvUserType.setText("当前身份：未知");
        }
    }

    private void createBlinkAnimation() {
        ObjectAnimator alphaAnimator = ObjectAnimator.ofFloat(takePhotoContainer, "alpha", 1.0f, 0.7f, 1.0f);
        alphaAnimator.setDuration(2000);
        alphaAnimator.setRepeatCount(ObjectAnimator.INFINITE);
        alphaAnimator.setRepeatMode(ObjectAnimator.RESTART);

        ObjectAnimator scaleXAnimator = ObjectAnimator.ofFloat(takePhotoContainer, "scaleX", 1.0f, 1.02f, 1.0f);
        scaleXAnimator.setDuration(2000);
        scaleXAnimator.setRepeatCount(ObjectAnimator.INFINITE);
        scaleXAnimator.setRepeatMode(ObjectAnimator.RESTART);

        ObjectAnimator scaleYAnimator = ObjectAnimator.ofFloat(takePhotoContainer, "scaleY", 1.0f, 1.02f, 1.0f);
        scaleYAnimator.setDuration(2000);
        scaleYAnimator.setRepeatCount(ObjectAnimator.INFINITE);
        scaleYAnimator.setRepeatMode(ObjectAnimator.RESTART);

        blinkAnimator = new AnimatorSet();
        blinkAnimator.playTogether(alphaAnimator, scaleXAnimator, scaleYAnimator);
        blinkAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
    }

    private void createRippleAnimation() {
        ObjectAnimator rippleScaleX = ObjectAnimator.ofFloat(rippleEffect, "scaleX", 0.8f, 1.3f, 0.8f);
        rippleScaleX.setDuration(2000);
        rippleScaleX.setRepeatCount(ObjectAnimator.INFINITE);
        rippleScaleX.setRepeatMode(ObjectAnimator.RESTART);

        ObjectAnimator rippleScaleY = ObjectAnimator.ofFloat(rippleEffect, "scaleY", 0.8f, 1.3f, 0.8f);
        rippleScaleY.setDuration(2000);
        rippleScaleY.setRepeatCount(ObjectAnimator.INFINITE);
        rippleScaleY.setRepeatMode(ObjectAnimator.RESTART);

        ObjectAnimator rippleAlpha = ObjectAnimator.ofFloat(rippleEffect, "alpha", 0.2f, 0.8f, 0.2f);
        rippleAlpha.setDuration(2000);
        rippleAlpha.setRepeatCount(ObjectAnimator.INFINITE);
        rippleAlpha.setRepeatMode(ObjectAnimator.RESTART);

        ObjectAnimator rippleRotation = ObjectAnimator.ofFloat(rippleEffect, "rotation", 0f, 360f);
        rippleRotation.setDuration(4000);
        rippleRotation.setRepeatCount(ObjectAnimator.INFINITE);
        rippleRotation.setRepeatMode(ObjectAnimator.RESTART);

        rippleAnimator = new AnimatorSet();
        rippleAnimator.playTogether(rippleScaleX, rippleScaleY, rippleAlpha, rippleRotation);
        rippleAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
    }

    private void startBlinkAnimation() {
        if (blinkAnimator != null && !blinkAnimator.isRunning()) {
            blinkAnimator.start();
        }
    }

    private void startRippleAnimation() {
        if (rippleAnimator != null && !rippleAnimator.isRunning()) {
            rippleAnimator.start();
        }
    }

    private void stopBlinkAnimation() {
        if (blinkAnimator != null && blinkAnimator.isRunning()) {
            blinkAnimator.cancel();
        }
    }

    private void stopRippleAnimation() {
        if (rippleAnimator != null && rippleAnimator.isRunning()) {
            rippleAnimator.cancel();
        }
    }

    private void addClickAnimation(View view) {
        ObjectAnimator scaleX = ObjectAnimator.ofFloat(view, "scaleX", 1.0f, 0.95f, 1.0f);
        ObjectAnimator scaleY = ObjectAnimator.ofFloat(view, "scaleY", 1.0f, 0.95f, 1.0f);

        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.play(scaleX).with(scaleY);
        animatorSet.setDuration(150);
        animatorSet.start();
    }

    private boolean checkLastWeekWrongQuestions() {
        try {
            return true;
        } catch (Exception e) {
            Log.e("MainActivity", "Error checking last week wrong questions", e);
            return false;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        updateRedDotStatus();
        registerRedDotReceiver();
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterRedDotReceiver();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterRedDotReceiver();
    }

    private void registerRedDotReceiver() {
        if (redDotUpdateReceiver == null) {
            redDotUpdateReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    if (intent != null && "com.iflytek.aidemo.action.UPDATE_RED_DOT".equals(intent.getAction())) {
                        Log.d("MainActivity", "Received red dot update broadcast");
                        updateRedDotStatus();
                    }
                }
            };

            IntentFilter filter = new IntentFilter("com.iflytek.aidemo.action.UPDATE_RED_DOT");
            LocalBroadcastManager.getInstance(this).registerReceiver(redDotUpdateReceiver, filter);
        }
    }

    private void unregisterRedDotReceiver() {
        if (redDotUpdateReceiver != null) {
            try {
                LocalBroadcastManager.getInstance(this).unregisterReceiver(redDotUpdateReceiver);
            } catch (Exception e) {
                Log.e("MainActivity", "Error unregistering red dot receiver", e);
            }
            redDotUpdateReceiver = null;
        }
    }

    private void updateRedDotStatus() {
        try {
            if (redDotWrongBook == null) {
                redDotWrongBook = findViewById(R.id.red_dot_wrong_book);
                if (redDotWrongBook == null) {
                    Log.e("MainActivity", "Could not find red_dot_wrong_book view");
                    return;
                }
            }

            boolean pending = WrongPushStore.hasPending(this);
            String weekKey = WrongPushStore.currentWeekKey();
            boolean afterMon9 = WrongPushStore.isAfterThisMondayNine();

            User currentUser = sessionManager != null ? sessionManager.getCurrentUser() : null;
            if (currentUser == null || currentUser.getUserId() == null || currentUser.getUserId().isEmpty()) {
                Log.e("MainActivity", "No valid user ID found, cannot check red dot status");
                redDotWrongBook.setVisibility(View.GONE);
                return;
            }

            String userId = currentUser.getUserId();

            boolean cleared = WrongPushStore.isClearedForWeek(this, userId, weekKey);

            boolean hasLastWeekWrongQuestions = checkLastWeekWrongQuestions();

            boolean show = pending || (afterMon9 && !cleared && hasLastWeekWrongQuestions);

            Log.d("MainActivity", String.format(
                    "Red dot status - userId: %s, weekKey: %s, pending: %b, afterMon9: %b, cleared: %b, hasLastWeekWrongQuestions: %b, show: %b",
                    userId, weekKey, pending, afterMon9, cleared, hasLastWeekWrongQuestions, show
            ));

            redDotWrongBook.setVisibility(show ? View.VISIBLE : View.GONE);

        } catch (Exception e) {
            Log.e("MainActivity", "Error updating red dot status", e);
            if (redDotWrongBook != null) {
                redDotWrongBook.setVisibility(View.GONE);
            }
        }
    }
}
